package gk.cxd.friday.controller;


import gk.cxd.friday.common.constant.Constants;
import gk.cxd.friday.common.result.RestResult;
import gk.cxd.friday.common.security.LoginUser;
import gk.cxd.friday.common.security.service.SysLoginService;
import gk.cxd.friday.common.security.service.SysPermissionService;
import gk.cxd.friday.common.security.service.TokenService;
import gk.cxd.friday.model.vo.SysMenuVO;
import gk.cxd.friday.model.vo.SysUserVO;
import gk.cxd.friday.service.SysMenuService;
import gk.cxd.friday.utils.http.ServletUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 登录验证
 */
@RestController
public class SysLoginController {
    @Autowired
    SysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    TokenService tokenService;

    @Autowired
    private SysLoginService loginService;
    /**
     * 登录方法
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @PostMapping({"/login", "/"})
    public RestResult login(String username, String password, String uuid) {
        System.out.println("/login: username["+username+"]"+"password: ["+password+"]"+"uuid: ["+uuid+"]");
        RestResult ajax = RestResult.success();
        // 生成令牌
        String token = loginService.login(username, password, "123", uuid);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取路由信息
     * @return
     */
    @GetMapping("/getRouters")
    public RestResult getRouters(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUserVO user = loginUser.getUser();
        List<SysMenuVO> menus =
                menuService.selectMenuTreeByUserId(user.getUserId());
        return RestResult.success(menuService.buildMenus(menus));
    }
    /**
     * 获取登录用户的授权信息
     */
    @GetMapping("getInfo")
    public RestResult getInfo(){
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUserVO user = loginUser.getUser();
        //角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        //权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        RestResult ajax = RestResult.success();
        ajax.put("user",user);
        ajax.put("roles",roles);

        ajax.put("permissions",permissions);
        System.out.println(permissions);
        return ajax;
    }
}
